/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import com.sun.xml.internal.ws.util.xml.DummyLocation;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import protocol.Message;

/**
 *
 * @author Acer
 */
public class GuiClient extends JFrame{
    
    //Kelas client
    Client client;
    
    //Boolean untuk syn
    
    
    /*
     * Constructor untuk GuiClient
     */
    public GuiClient(){
        InitUI();
        InitLoginUI();
    }
    
    public int Open8boxMode = MAKE_NEW_FOLDER;
    
    public final static int MAKE_NEW_FOLDER = 20;
    public final static int OPEN_ALREADY_FOLDER = 21;
    public final static int MOVE_ALREADY_FOLDER = 22;
    
    public final static int LOGIN_WIDTH = 10;
    JPanel m_LoginPanel;//Panel jika berhasil login
    JPanel m_SynchPanel;//Panel jika sudah connect
    
    JButton m_LoginButton;
    JButton m_LogoutButton;
    JTextField m_UsernameField;
    JPasswordField m_PasswordField;
    
    JLabel passwordLabel;
    JLabel usernameLabel;
    
    JPanel userPanel;
    JPanel passwordPanel;
    
    //JFileChooser untuk pilih folder atau file baru
    JFileChooser m_JFileChooser;
    JButton m_SelectNewFolderButton;
    JButton m_SelectPreparedFolderButton;
    JButton m_MovePreparedFolderButton;
    /**
     * Construct GUI
     */
    public void InitUI(){
        m_SynchPanel = new JPanel();
        
        m_LogoutButton = new JButton("Logout");
        m_LogoutButton.addActionListener(actionLogout());
        
        m_JFileChooser = new JFileChooser();
        m_JFileChooser.setDialogTitle("Choose a file");
        m_JFileChooser.setVisible(true);
        m_JFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        m_JFileChooser.setAcceptAllFileFilterUsed(false);
        
        m_SelectNewFolderButton= new JButton("Make new 8box");
        m_SelectNewFolderButton.addActionListener(actionSelectNewFolder());
        
        m_SelectPreparedFolderButton = new JButton("Select from your directory");
        m_SelectPreparedFolderButton.addActionListener(actionSelectAlreadyFolder());
        
        m_MovePreparedFolderButton = new JButton("Move your 8box");
        m_MovePreparedFolderButton.addActionListener(actionMovePreparedFolder());
        
        m_LoginPanel = new JPanel();
        m_LoginPanel.setLayout(new FlowLayout());
        m_LoginPanel.setVisible(true);
        
        m_UsernameField = new JTextField(LOGIN_WIDTH);
        m_UsernameField.setPreferredSize(new Dimension(100, 20));
        usernameLabel = new JLabel("Masukkan username : ");
        usernameLabel.setLabelFor(m_UsernameField);
        userPanel = new JPanel();
        userPanel.add(usernameLabel);
        userPanel.add(m_UsernameField);
        
        m_PasswordField = new JPasswordField(LOGIN_WIDTH);        
        m_PasswordField.setPreferredSize(new Dimension(100, 20));
        passwordLabel = new JLabel("Masukkan password : ");
        passwordLabel.setLabelFor(m_PasswordField);
        passwordPanel = new JPanel();
        passwordPanel.add(passwordLabel);
        passwordPanel.add(m_PasswordField);
        
        m_LoginButton = new JButton("Login");
        m_LoginButton.setPreferredSize(new Dimension(100, 20));
        m_LoginButton.setToolTipText("Press button for login");
        m_LoginButton.addActionListener(actionLogin());
        
        this.setTitle("8box client");
        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
    }
    
    public void InitLoginUI(){
        m_SynchPanel.setVisible(false);
        m_LoginPanel.setVisible(true);
        this.getContentPane().add(m_LoginPanel);
        m_LoginPanel.add(userPanel);
        m_LoginPanel.add(passwordPanel);
        m_LoginPanel.add(m_LoginButton);
        m_LoginPanel.add(m_SelectNewFolderButton);
        m_LoginPanel.add(m_SelectPreparedFolderButton);
    }
    
    public void InitSynchronizeUI(){
        m_LoginPanel.setVisible(false);
        m_SynchPanel.setVisible(true);
        this.getContentPane().add(m_SynchPanel);
        m_SynchPanel.add(m_LogoutButton);
        m_SynchPanel.add(m_MovePreparedFolderButton);
//        m_SynchPanel.add(m_JFileChooser);
//        if (m_JFileChooser.showOpenDialog(new JFrame())==JFileChooser.APPROVE_OPTION){
//            System.out.println("Curr dir : " + m_JFileChooser.getCurrentDirectory());
//            System.out.println("Selected file : " + m_JFileChooser.getSelectedFile());
//        }
        
    }
    
    public ActionListener actionMovePreparedFolder(){
        ActionListener res = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (m_JFileChooser.showOpenDialog(new JFrame())==JFileChooser.APPROVE_OPTION){
                    System.out.println("Mulai pindahkan folder ke folder 8box baru");
                    utility.Utility.MoveDirectory(client.clientDirectory, m_JFileChooser.getSelectedFile().toString());
                    client.setClientDirectory(m_JFileChooser.getSelectedFile().toString()+"\\"+Client.APPS_NAME);
                }
            }
        };
        return res;
    }
    
    public ActionListener actionSelectNewFolder(){
        ActionListener res = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (m_JFileChooser.showOpenDialog(new JFrame())==JFileChooser.APPROVE_OPTION){
                    System.out.println("Mulai buat folder 8box baru : " + m_JFileChooser.getSelectedFile().toString());
                    client.setClientDirectory(m_JFileChooser.getSelectedFile().toString()+"\\"+Client.APPS_NAME);
                    if (utility.Utility.CreateNewDirectory(client.getClientDirectory())){
                        System.out.println("Berhasil create directory");
                    }else{
                        System.out.println("Tidak berhasil create directory");
                    }
                }
            }
        };
        return res;
    }
    
    public ActionListener actionSelectAlreadyFolder(){
        ActionListener res = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (m_JFileChooser.showOpenDialog(new JFrame())==JFileChooser.APPROVE_OPTION){
                    System.out.println("Ambil dari 8 box yang sudah ada, nama file : " + m_JFileChooser.getSelectedFile().toString());
                    client.setClientDirectory(m_JFileChooser.getSelectedFile().toString());
                }
            }
        };
        return res;
    }
    
    public ActionListener actionLogout(){
        ActionListener res = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    try {
                        client.Logout();
                    } catch (UnsupportedEncodingException ex) {
                        Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    InitLoginUI();
                } catch (IOException ex) {
                    System.out.println("Not success logout");
                }
            }
        };
        return res;
    }
    /**
     * ActionListener untuk login
     */
    public ActionListener actionLogin(){
        ActionListener res = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    m_SynchPanel = new JPanel();
//                    m_LoginPanel.setVisible(false);
                    GuiClient.this.add(m_SynchPanel);
                    String username = GuiClient.this.m_UsernameField.getText();
                    String password = GuiClient.this.m_PasswordField.getText();
//                    String username = "novan";
//                    String password = "12345678";
                    client.setUsername(username);
                    client.setPassword(password);
                    System.out.println("Username : " + username);
                    System.out.println("Password : " + password);
                    client.Login(username, password);
                    byte[] b = new byte[1000];
                    client.bisSocket.read(b);
                    String result = Message.byteToString(b);
                    System.out.println("Dari server : " + result);
                    if (result.trim().equals("Login success!")){
                        client.isStillLogin = true;
                        InitSynchronizeUI();
//                        client.synchronizeThread.start();
//                        client.synchronizeThread.run();
                    }
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        return res;
    }
    
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException{
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                GuiClient guiClient = new GuiClient();
                guiClient.setVisible(true);
                guiClient.client = new Client();
            }
        });
//        GuiClient guiClient = new GuiClient();
//        guiClient.client.Login("novan", "12345678");
//        byte[] b = new byte[1000];
//        guiClient.client.bisSocket.read(b);
//        String result = Message.byteToString(b);
//        System.out.println("Dari server : " + result);
//        if (result.trim().equals("Login success!")){
//            System.out.println("START kirim");
//            guiClient.client.isStillLogin = true;
//            guiClient.client.synchronizeThread.start();
//        }else{
//            System.out.println("NOT START kirim");
//        }
//        
//        boolean lho = true;
//        while (lho){
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException ex) {
//                Logger.getLogger(GuiClient.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            System.out.println("EAAA");
//        }
//        System.out.println("ENDING");
    }
}
